#coding=utf-8
__author__ = 'liangdong'
from numpy import *
import random
import math
class userBasedCF:
    def UserSimilarity_test(self,train):
        W=dict()
        for u in train.keys():
            for v in train.keys():
                if u == v:
                    continue
                W.setdefault(u,{})
                W[u][v] = len(set(train[u].keys()) & set(train[v].keys()))
                W[u][v] /= math.sqrt(len(train[u])*len(train[v])*1.0)
        return W

    ##计算相似度：对稀疏矩阵进行了优化
    def  UserSimilarity(train):
        ##把用户，商品[多个]表，转换为商品，用户[多个]表
        item_users = dict()
        for u,items in train.items():
            for i in items.keys():
                if i not in item_users:
                    item_users[i]=set()
                item_users[i].add(u)
        ##生成用户同线矩阵（值为商品数）
        C = dict()
        N = dict()
        for i,users in item_users.items():
            for u in users:
                N.setdefault(u,0)
                N[u] += 1
                for v in users:
                    if u == v:
                        continue
                    C.setdefault(u,{})
                    C[u].setdefault(v,0)
                    C[u][v] += 1
        ##生成用户同线矩阵（值为相似度）
        W = dict()
        for u,related_users in C.items():
            W.setdefault(u,dict())
            for v,cuv in related_users.items():
                W[u][v] = cuv / math.sqrt(N[u] * N[v])
        print W

    def Recommend(user,train,W):
       pass
